/*
 * @Author: 颜礼田 2564217790@qq.com
 * @Date: 2024-09-07 11:15:53
 * @LastEditors: MrDotYan 2564217790@qq.com
 * @LastEditTime: 2024-09-27 11:06:23
 * @FilePath: /webServer/src/controller/user/user.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import {
  Body,
  Controller,
  Del,
  Get,
  Inject,
  Post,
  Put,
  Query,
} from '@midwayjs/core';
import { UserService } from '../../service/user/user.service';
import { Validate } from '@midwayjs/validate';
import {
  ChangePwdValidator,
  ListParamsValidator,
  StrIdValidator,
} from '../../validator';
import {
  EditUserValidator,
  SaveUserValidator,
} from '../../validator/user/user';
import { DepartmentService } from '../../service/department/department.service';
import { RoleService } from '../../service/role/role.service';
import { isNotEmpty } from '../../utils/isHelper';
import { BadRequestError } from '@midwayjs/core/dist/error/http';
import { uniqueByProps } from '../../utils/toolsHelper';
import { CaptchaService } from '@midwayjs/captcha';
import { UserSchema } from '../../schema';

@Controller('/user', { tagName: '' })
export class UserController {
  @Inject()
  userService: UserService;

  @Inject()
  deptService: DepartmentService;

  @Inject()
  roleService: RoleService;

  @Inject()
  captchaService: CaptchaService;

  @Post('/list', { summary: '列表' })
  @Validate()
  async list(@Body() body: ListParamsValidator<UserSchema>) {
    const data = await this.userService.list(body);
    return Object.assign(data, body);
  }

  @Post('/save', { summary: '保存' })
  @Validate()
  async save(@Body() body: SaveUserValidator) {
    const dept = await this.deptService.info(body.dept.id);
    Object.assign(body, { dept: dept });
    const role = await this.roleService.findByIds(
      body.role?.map(ele => ele.id)
    );
    Object.assign(body, { role: role });
    return await this.userService.save(body);
  }

  @Get('/info', { summary: '信息' })
  @Validate()
  async info(@Query() body: StrIdValidator) {
    return await this.userService.info(body.id);
  }

  @Del('/remove', { summary: '删除' })
  @Validate()
  async remove(@Query() body: StrIdValidator) {
    return await this.userService.remove(body.id);
  }

  @Del('/delete', { summary: '（真）删除' })
  @Validate()
  async realRemove(@Query() body: StrIdValidator) {
    return await this.userService.realRemove(body.id);
  }

  @Put('/edit', { summary: '编辑' })
  @Validate()
  async edit(@Query() query: StrIdValidator, @Body() body: EditUserValidator) {
    const user = await this.userService.info(query.id);
    Object.assign(user, body);
    const dept = await this.deptService.info(body.dept.id);
    Object.assign(user, { dept: dept });
    const role = await this.roleService.findByIds(
      body.role?.map(ele => ele.id)
    );
    Object.assign(user, { role: role });
    return await this.userService.save(user);
  }

  @Get('/permission', { summary: '通过用户ID，获取权限列表' })
  @Validate()
  async permissionList(@Query() query: StrIdValidator) {
    const user = await this.userService.info(query.id);
    if (isNotEmpty(user)) {
      const { role } = user;
      if (isNotEmpty(role)) {
        const roles = await this.roleService.findByIds(
          role.map(ele => ele.id),
          true
        );

        return uniqueByProps(
          roles.map(ele => ele.permission).flat(Infinity),
          'id'
        );
      }
    }
    throw new BadRequestError('用户或权限不存在/Not Found');
  }

  @Put('/changePwd')
  @Validate()
  async changePwd(
    @Query() query: StrIdValidator,
    @Body() body: ChangePwdValidator
  ) {
    const user = await this.userService.info(query.id);
    const pass = await this.captchaService.check(body.codeKey, body.code);
    if (pass) {
      return await this.userService.save(
        Object.assign(user, { password: body.password })
      );
    }

    throw new BadRequestError('验证码错误或已过期');
  }
}
